#include "EventEngine/ExcutorPool.h"

#include <random>

namespace NTrader
{

void ExcutorPool::Start()
{
	for (unsigned int i = 0; i < std::thread::hardware_concurrency() * 2; i++)
	{
		Excutor_t excutor = std::make_shared<Excutor>();
		excutor->Start();
		__pool.push_back(excutor);
	}
}

void ExcutorPool::Stop()
{
	for (auto item : __pool)
	{
		item->Stop();
	}
}

void ExcutorPool::Dispatch(Actor_t a, Event_t e)
{
	a->Post(e);

	//random choose
	int status = IActor::ActorStatus::WAITING;
	if( a->_status.compare_exchange_strong(status
											, IActor::ActorStatus::EXECUTING
											, std::memory_order_relaxed
											, std::memory_order_relaxed))
	{
		//std::default_random_engine generator;
		//std::uniform_int_distribution<size_t> distribution(0, __pool.size());
		//size_t number = distribution(generator);
		size_t number = _index++%__pool.size();
		Excutor_t excutor = __pool.at(number);
		excutor->Post(a);
	}	
}

}
